package com.youlin.untils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.youlin.dto.res.OSSResDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;

@Component
public class OSSUtil {

    @Value("${oss.accessId}")
    private String accessId;
    @Value("${oss.accessKey}")
    private String accessKey;
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.bucket}")
    private String bucket;

    public OSSResDto getOSSsignature (String dir) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); // 用户上传文件时指定的前缀。

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            return new OSSResDto().setAccessid(accessId).setPolicy(encodedPolicy).setSignature(postSignature)
                    .setDir(dir).setHost("https://" + bucket + "." + endpoint).setExpire(String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            return null;
        } finally {
            ossClient.shutdown();
        }
    }

    public String upload(MultipartFile uploadFile) {
        String fileName = uploadFile.getOriginalFilename();
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
            if (! ossClient.doesBucketExist(this.bucket)) ossClient.createBucket(this.bucket);
            ossClient.putObject(this.bucket, fileName, uploadFile.getInputStream());
            return "https://" + bucket + ".oss-cn-beijing.aliyuncs.com/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally { // 关闭OSSClient
            if (ossClient != null) ossClient.shutdown();
        }
    }

}
